//
//  MyShoppingCarViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/9/29.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "MyShoppingCarViewController.h"
#import "MyShoppingCarCell.h"
@interface MyShoppingCarViewController ()<UITableViewDelegate,UITableViewDataSource>{
    NSInteger totalNumber;
    float priceValue;
}
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UIImageView *centerImageView;
@property(nonatomic,strong)UILabel *numLabel;
@property(nonatomic,strong)UILabel *totalLabel;
@property(nonatomic,strong)UILabel *priceLabel;
@property (strong, nonatomic) NSMutableArray<CALayer *> *redLayers;

@property (strong, nonatomic) NSArray *priceArr;




/**
 编辑
 */
@property (nonatomic, strong) UIButton *rightBtn;

/**
 删除
 */
@property (nonatomic, strong) UIButton *deleteBtn;

/**
 全选
 */
@property (nonatomic, strong) UIButton *allBtn;
@property (nonatomic, strong) NSMutableArray *selectArray;

@property(nonatomic,strong)UIView *bottomView;

@end

@implementation MyShoppingCarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"购物车";
    [self setupChildViews];
    [self createNavagationBackBtn];
    [self createUIOfTableview];
    // Do any additional setup after loading the view.
}
-(void)createNavagationBackBtn{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 6, 67, 23);
    UIImageView *backImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigator_btn_back"]];
    backImg.frame = CGRectMake(-10, 0, 22, 22);
    [backBtn addSubview:backImg];
    UILabel *backText = [[UILabel alloc] initWithFrame:CGRectMake(12, 0, 65, 22)];
//    backText.text = @"返回";
    backText.font = [UIFont systemFontOfSize:17];
    [backText setBackgroundColor:[UIColor clearColor]];
    [backText setTextColor:[UIColor whiteColor]];
    [backBtn addSubview:backText];
    [backBtn addTarget:self action:@selector(leftBarButtonItemPressed:) forControlEvents:UIControlEventTouchUpInside];
    [backImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backBtn.mas_left).offset(-10);
        make.centerY.equalTo(backBtn.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(22, 22));
    }];
    [backText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backImg.mas_right).offset(2);
        make.centerY.equalTo(backBtn.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(65, 22));
    }];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    [self.navigationItem setLeftBarButtonItem:leftButton];
}
-(void)leftBarButtonItemPressed:(UIButton *)btn{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)createUIOfTableview{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[MyShoppingCarCell class] forCellReuseIdentifier:@"MyShoppingCarCell"];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = [UIColor yellowColor];
    _totalLabel = [[UILabel alloc] init];
    [self.view addSubview:_totalLabel];
    [_totalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.bottom.equalTo(self.view);
        make.top.equalTo(self.tableView.mas_bottom);
        make.width.mas_equalTo(WIDTH * 0.7);
    }];
    UIButton *commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:commitBtn];
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.and.bottom.equalTo(self.view);
        make.top.equalTo(self.tableView.mas_bottom);
        make.left.equalTo(_totalLabel.mas_right);
    }];
    [self showBottomUI];
    commitBtn.backgroundColor = [UIColor yellowColor];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 10;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyShoppingCarCell *inforCell = [tableView dequeueReusableCellWithIdentifier:@"MyShoppingCarCell"];
    NSString *str = [NSString stringWithFormat:@"%@ %@",@"￥",@"10"];
    inforCell.selectionStyle = UITableViewCellSelectionStyleNone;
    inforCell.priceLabel.text = str;
    [inforCell setPlusTapHandle:^(CGPoint position) {
        totalNumber++;
        priceValue += [self.priceArr[indexPath.row] floatValue];
        [self updateNumberLabel];
    }];
    
    [inforCell setMinusTapHandle:^() {
        totalNumber--;
        priceValue -= [self.priceArr[indexPath.row] floatValue];
        [self updateNumberLabel];
    }];
    return inforCell;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return scaleTopAndBottom(100.f);
}
- (void)initCHLayerFromPoint:(CGPoint)startPoint toPoint:(CGPoint)endPoint {
    
    CALayer *chLayer = [[CALayer alloc] init];
    [self.redLayers addObject:chLayer];
    
    chLayer.frame = CGRectMake(startPoint.x, startPoint.y, 15, 15);
    chLayer.cornerRadius = CGRectGetWidth(chLayer.frame)/2.f;
    chLayer.backgroundColor = [UIColor redColor].CGColor;
    [self.view.layer addSublayer:chLayer];
    
    CAKeyframeAnimation *CHAnimation=[CAKeyframeAnimation animationWithKeyPath:@"position"];
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, startPoint.x, startPoint.y);
    CGPathAddQuadCurveToPoint(path, NULL, endPoint.x, startPoint.y, endPoint.x, endPoint.y);
    
    CHAnimation.path = path;
    CHAnimation.removedOnCompletion = NO;
    CHAnimation.fillMode = kCAFillModeBoth;
    CHAnimation.duration = 0.5;
    CHAnimation.delegate = self;
    
    [chLayer addAnimation:CHAnimation forKey:nil];
    
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    [self.redLayers[0] removeFromSuperlayer];
    [self.redLayers removeObjectAtIndex:0];
    
}

- (void)updateNumberLabel{
    NSString *totalNumberStr = [NSString stringWithFormat:@"共 %zd 件商品",totalNumber];
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:totalNumberStr];
    [attributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16.f] range:NSMakeRange(1, attributedStr.length - 4)];
    self.numLabel.attributedText = attributedStr;
    NSMutableAttributedString *totalLabelStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%.2f",@"合计:￥",priceValue]];
    [totalLabelStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,2)];
    [totalLabelStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3, totalLabelStr.length-3)];
    self.totalLabel.attributedText = totalLabelStr;
    NSMutableAttributedString *priceLabelStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%.2f",@"小计:￥",priceValue]];
    [priceLabelStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, 2)];
    [priceLabelStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3, priceLabelStr.length-3)];
    self.priceLabel.attributedText = priceLabelStr;
}
-(NSArray *)priceArr{
    if (_priceArr == nil) {
        _priceArr = @[@"15.8",@"30.4",@"80",@"100",@"200"];
    }
    return _priceArr;
}
- (NSMutableArray<CALayer *> *)redLayers {
    if (!_redLayers) {
        _redLayers = [NSMutableArray array];
    }
    return _redLayers;
}
#pragma makr - 删除功能的实现
- (void)setupChildViews {
    UIBarButtonItem *spatce = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    UIBarButtonItem *rightBaritem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
    spatce.width = -10;
    self.navigationItem.rightBarButtonItems = @[spatce,rightBaritem];
    //    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.deleteBtn];
    
}
- (UIButton *)rightBtn {
    if (!_rightBtn) {
        _rightBtn = [[UIButton alloc] init];
        [_rightBtn setTitle:@"编辑" forState:UIControlStateNormal];
        [_rightBtn setTitle:@"完成" forState:UIControlStateSelected];
        
        [_rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        [_rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [_rightBtn sizeToFit];
    }
    return _rightBtn;
}

- (void)rightBtnAction {
    self.rightBtn.selected = !self.rightBtn.isSelected;
    self.deleteBtn.hidden = !self.rightBtn.isSelected;
    self.allBtn.hidden = !self.rightBtn.isSelected;
    if (self.rightBtn.isSelected) {
        [self.tableView setEditing:YES animated:YES];
        [self showBottomUI];
    }else{
        [self.tableView setEditing:NO animated:YES];
        [self removebackView];
    }
}
-(void)showBottomUI{
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0,HEIGHT - 49, WIDTH, 49)];
    [self setUIAbovewView:_bottomView];
    [self.view addSubview:_bottomView];
    [self.view bringSubviewToFront:_bottomView];
    _bottomView.backgroundColor = [UIColor whiteColor];
//    [UIView animateWithDuration:0.1 animations:^{
//        _bottomView.frame = CGRectMake(0,HEIGHT - 49, WIDTH, 49);
//    }];
}
-(void)removebackView{
    
    [UIView animateWithDuration:0.1 animations:^{
        [_bottomView removeFromSuperview];
    }];
}
-(void)setUIAbovewView:(UIView *)view{
    UIImageView *imageView = [[UIImageView alloc] init];
    [view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view);
        make.left.equalTo(view.mas_left).offset(12);
        make.size.mas_equalTo(CGSizeMake(16, 16));
    }];
    UIButton *subBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    subBtn.backgroundColor = [UIColor redColor];
    [subBtn setTitle:@"结算" forState:UIControlStateNormal];
    [subBtn setTitleColor:[UIColor whiteColor] forState:0];
    [view addSubview:subBtn];
    [subBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.bottom.equalTo(view);
        make.width.mas_equalTo(scaleLeftAndRight(100));
    }];
    _priceLabel = [[UILabel alloc] init];
    _priceLabel.textAlignment = NSTextAlignmentRight;
    [view addSubview:_priceLabel];
    [_priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_top);
        make.right.equalTo(subBtn.mas_left).offset(-10);
        make.width.mas_equalTo(scaleLeftAndRight(120));
        make.height.mas_equalTo(scaleTopAndBottom(25.f));
    }];
    UILabel *insLabel = [[UILabel alloc] init];
    insLabel.text = @"不含运费";
    insLabel.textAlignment = NSTextAlignmentRight;
    [view addSubview:insLabel];
    [insLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_priceLabel.mas_bottom);
        make.right.equalTo(subBtn.mas_left).offset(-10);
        make.width.mas_equalTo(scaleLeftAndRight(120));
        make.height.mas_equalTo(scaleTopAndBottom(15.f));
    }];
//    self.numLabel = [[UILabel alloc] init];
//    [view addSubview:_numLabel];
//    [_numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerY.equalTo(view.mas_centerY);
//        make.right.equalTo(_priceLabel.mas_left).offset(scaleLeftAndRight(-20));
//        make.left.equalTo(view.mas_left);
//        make.height.mas_equalTo(scaleTopAndBottom(25.f));
//    }];
//    _priceLabel.backgroundColor = [UIColor orangeColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
